<?php

namespace App\Services;

use Elasticsearch\ClientBuilder;

class Es
{
    public function __construct(){
        $this->client=ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
    }

    /**
     * 初始化数据
     * @param $data
     * @return array|callable
     */
    public function add($data){
        foreach ($data as $val){
            $params=[
              'index'=>'data',
              'type'=>'_doc',
              'id'=>$val['id'],
              'body'=>$val
            ];
            $response = $this->client->index($params);
        }
        return $response;
    }

    /**
     * 创建索引  分词器
     * @param $index
     * @param $type
     * @param $field
     * @return array
     */
    public function creation_index($index,$type,$field){
        $params = [
            'index' => $index,
            'body' => [
                'mappings' => [
                    $type=>[
                        '_source'=>[
                            'enabled'=>true
                        ],
                        'properties'=>[
                            $field=>[
                                'type'=>'text',
                                'analyzer'=>'ik_smart',//ik分词器
                            ]
                        ]
                    ]
                ]
            ],
            'include_type_name' => true,
        ];
        $response = $this->client->indices()->create($params);
        return $response;
    }

    /**
     * 搜索
     * @param $name
     * @return array
     */
    public function search($name){
        $params = [
            'index' => 'data',
            'type' => '_doc',
            'body' => [
                'query' => [
                    'match' => [
                        'meeting_title' => $name
                    ]
                ],
                'highlight'=>[
                    'fields'=>[
                        "meeting_title"=>[
                            'pre_tags'=>["<span style='color: red'>"],
                            'post_tags'=>["</span>"]
                        ]
                    ]
                ]
            ]
        ];
        //处理数据
        $results=$this->client->search($params);
        $data=$results['hits']['hits'];
        foreach ($data as $k=>$v){
                $data[$k]['_source']['meeting_title']=$v['highlight']['meeting_title'][0];

        }
        $title=array_column($data,'_source');
        return $title;
    }

}
